from flask import request
from flask_restful import Resource
from common.resp import ajax_data, ajax_page, ajax_error, ajax_success
from core import db
from datetime import datetime
import hashlib

class UserModel(db.Model):
    __tablename__ = "sys_user"

    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    account = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(100))
    nickname = db.Column(db.String(50))
    phone = db.Column(db.String(50))
    email = db.Column(db.String(50))
    status = db.Column(db.CHAR(1), default='1')
    role = db.Column(db.String(20), default='admin')
    create_time = db.Column(db.DateTime, default=datetime.now)
    update_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
    login_time = db.Column(db.DateTime)

    def to_json(self):
        return {
            'id': self.id,
            'account': self.account,
            'nickname': self.nickname,
            'email': self.email,
            'phone': self.phone,
            'status': self.status,
            'role': self.role,
            'login_time': self.login_time.strftime('%Y-%m-%d %H:%M:%S') if self.login_time else None
        }
  
    @staticmethod
    def md5_encrypt(password):
        md5 = hashlib.md5()
        md5.update(password.encode('utf-8'))
        return md5.hexdigest()
        
class UserResource(Resource):
    def get(self):
        query = request.args;
        filters = []
        if query.get('nickname'):
            filters.append(UserModel.nickname.like('%' + query['nickname'] + '%'))
        if query.get('status'):
            filters.append(UserModel.status == query['status'])
        if query.get('role'):
            filters.append(UserModel.role == query['role'])

        paginate = UserModel.query.filter(
            *filters).paginate(
            page=int(query.get('page', 1)), per_page=int(query.get('limit', 10)), error_out=False)

        return ajax_page([user.to_json() for user in paginate.items], paginate.total)

    def post(self):
        data = request.get_json()
        user = UserModel(
            account = data['account'],
            password = UserModel.md5_encrypt(data.get('password') if data.get('password') else '123456'),
            nickname = data['nickname'],
            phone = data['phone'],
            email = data['email'],
            status = '1',
            role = data.get('role', 'admin')
        )
        db.session.add(user)
        db.session.commit()
        return ajax_success('用户创建成功')

    def put(self):
        data = request.get_json()
        if not data.get('id'):
            return ajax_error('参数错误')

        user = UserModel.query.get_or_404(data.get('id'))
        if not user:
            return ajax_error('用户不存在')

        if data.get('password'):
            user.password = UserModel.md5_encrypt(data.get('password'))
        
        if data.get('nickname'):
            user.nickname = data.get('nickname', user.nickname)
        if data.get('status'):
            user.status = data.get('status', user.status)
        if data.get('phone'):
            user.phone = data.get('phone', user.phone)
        if data.get('email'):
            user.email = data.get('email', user.email)
        if data.get('role'):
            user.role = data.get('role', user.role)
        db.session.add(user)
        db.session.commit()
        return ajax_success('用户更新成功')



class UserDetail(Resource):
    def get(self, id):
        if id:
            user = UserModel.query.get_or_404(id)
            return ajax_data(user.to_json())
        else:
            return ajax_error('参数错误')

    def delete(self, id):
        user = UserModel.query.get_or_404(id)
        db.session.delete(user)
        db.session.commit()
        return ajax_success('用户删除成功')